package com.atguigu.gulimall.auth.controller;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberEntity;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Controller
public class LoginController {
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;
@PostMapping("/regist")
    public String  regist(@Valid UserRegistVo userRegistVo, BindingResult result, RedirectAttributes attributes){
    if(result.hasErrors()){
        List<FieldError> fieldErrors = result.getFieldErrors();
        Map<String, String> errorMap = fieldErrors.stream().collect(Collectors.toMap(
            FieldError::getField
                ,
                FieldError::getDefaultMessage
        ));
//        model.addAttribute("errors",errorMap);
        attributes.addFlashAttribute("errors",errorMap);
        return  "redirect:http://auth.gulimall.com/reg.html";
    }
    String code = userRegistVo.getCode();
    String codeFromRedis = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
    if(!StringUtils.isEmpty(codeFromRedis)){
        if(code.equals(codeFromRedis.split("_")[0])){
            //在这里,把验证码删除了, 因为用不上了
            stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
         //  调用注册逻辑
            R r = memberFeignService.regist(userRegistVo);
            if(r.getCode()==0){
                return   "redirect:http://auth.gulimall.com/login.html";
            }else{
                HashMap<String, String> errors = new HashMap<>();
                errors.put("msg","错误啦");//TODO
//                errors.put("msg",r.getData(new TypeReference<String>(){}));
                attributes.addFlashAttribute("errors",errors);
                return  "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return  "redirect:http://auth.gulimall.com/reg.html";
        }
    }else{
        HashMap<String, String> errors = new HashMap<>();
        errors.put("code","验证码错误");
        attributes.addFlashAttribute("errors",errors);
        return  "redirect:http://auth.gulimall.com/reg.html";
    }
}
    @GetMapping("/sms/sendCode")
    @ResponseBody
public  R  sendCode(@RequestParam String phone){
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
         if(!StringUtils.isEmpty(redisCode)){
             long l=Long.parseLong(redisCode.split("_")[1]);
             if(System.currentTimeMillis()-l< 60000){
                 return  R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
             }
         }
        String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone,code);
    return  R.ok();
}
@PostMapping("/login")
public String  login(UserLoginVo vo, RedirectAttributes attributes, HttpSession httpSession){
    R login = memberFeignService.login(vo);
    if(login.getCode()==0){
        LinkedHashMap<String,Object> map= (LinkedHashMap<String, Object>) login.get("data");
        MemberEntity member = new MemberEntity();
        String s = (String) map.get("nickname");
        member.setNickname(s);
        Integer id= (Integer) map.get("id");
        member.setId(Long.valueOf(id));
        httpSession.setAttribute("loginUser", member);
//        attributes.addFlashAttribute("loginUser",member);
    return "redirect:http://gulimall.com";
    }else{
        HashMap<String, String> errors = new HashMap<>();
        errors.put("msg","你错误啦啦~");
        attributes.addFlashAttribute("errors",errors    );
        return   "redirect:http://auth.gulimall.com/login.html";
    }
}
@GetMapping("/login.html")
public String  loginPage(HttpSession session, HttpServletRequest  request){
    HttpSession session1 = request.getSession(false);
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);  //loginUser
//    Object attribute = session.getAttribute("loginUser");
    if(attribute==null){  //    说明没有登录
    return  "login";
    }else{
        return  "redirect:http://gulimall.com";
    }
}
@GetMapping("/login2.html")
    public String login(){
    return  "login";
}
}
